package com.ruoyi.quartz.task;

import java.util.Date;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Device;
import com.ruoyi.system.service.IDeviceService;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("deviceTask")
public class DeviceTask {

	private static final Logger log = LoggerFactory.getLogger(DeviceTask.class);

	@Autowired
	private IDeviceService deviceService;

	public void deviceInfoSyn()
    {
        System.out.println("deviceTask 开始同步设备IP信息");
        String cmdResult = SaltFn.execCommand("sudo salt \"*\" grains.items");
        if(StringUtils.isNotEmpty(cmdResult)) {
        	JSONObject paramsObj = JSONObject.parseObject(cmdResult);
        	for (Entry entry : paramsObj.getInnerMap().entrySet()) {
        		String key = (String)entry.getKey();
        		Object object = SaltFn.getKeyValue(cmdResult,StringUtils.format("{}#ipv4", key));
        		if(object != null) {
        			//获取真实ip
        			String ip = SaltFn.getRealIp(object);
        			if(StringUtils.isEmpty(ip)) {
        				log.warn("{} ip is blank ", key);
        				continue;
        			}else {
        				log.info("{} ip is {} ", key,ip);
        			}
        			Device device = deviceService.selectDeviceByDeviceName(key);
        			if(device != null ) {
        				/*
        				 * 更新ip操作
        				 */
        				device.setIp(ip);
        				deviceService.updateDevice(device);
        			}else {
        				device = new Device();
        				device.setDeviceName(key);
        				device.setIp(ip);
        				device.setState("在线");
        				device.setCreateTime(new Date());
        				deviceService.insertDevice(device);
        			}
        		}
        	}
        }
    }

	public void deviceMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
		System.out.println(StringUtils.format("deviceTask 执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
	}

	public void deviceParams(String params) {
		System.out.println("deviceTask 执行有参方法：" + params);
	}

	public void deviceNoParams() {
		System.out.println("deviceTask 执行无参方法");
	}
	
	public static void main(String[] args) {
		new DeviceTask().deviceInfoSyn();
	}
}
